package user_session

import (
	"common-api/logs"
	"common-api/session"
	"sync"
	"time"
)

var UserSessions sync.Map

var SessionUsers sync.Map

var timer = time.NewTicker(5 * time.Second)

type UserSession struct {
	Username            string
	S                   *session.Session
	lastActiveTimestamp int64
}

/*func init() {
	// 设置一个 5 秒的定时器
	go func() {
		for {
			select {
			case <-timer.C:
				// 等待定时器触发
				TimeoutClean(60) // 执行定时任务
			}
		}
	}()
}*/

func New(username string, session *session.Session) {
	logs.Logger.Infof("add new user session: %s", username)
	userSession := &UserSession{Username: username, S: session, lastActiveTimestamp: time.Now().Unix()}
	UserSessions.Store(username, userSession)
	SessionUsers.Store(session, username)
}

func TimeoutClean(du int64) {
	UserSessions.Range(func(username, userSession interface{}) bool {
		if time.Now().Unix()-userSession.(*UserSession).lastActiveTimestamp >= du {
			logs.Logger.Infof("kill user session : %s", userSession.(*UserSession).Username)
			UserSessions.Delete(username)
			SessionUsers.Delete(userSession.(*UserSession).S)
			return false // 返回 false 退出遍历
		}
		return true // 返回 true 继续遍历
	})
}

func RenewUserSession(username string) {
	if userSession, ok := UserSessions.Load(username); ok {
		logs.Logger.Debugf("renew  user session : %s", username)
		userSession.(*UserSession).lastActiveTimestamp = time.Now().Unix()
	}
}

func GetUserSessionByUserName(username string) *UserSession {
	if userSession, ok := UserSessions.Load(username); ok {
		return userSession.(*UserSession)
	}
	return nil
}

func GetUserNameBySession(session *session.Session) string {
	if userSession, ok := SessionUsers.Load(session); ok {
		return userSession.(string)
	}
	return ""
}

func Close(session *session.Session) {
	if username, ok := SessionUsers.Load(session); ok {
		logs.Logger.Infof("disconnect user session : %s", username)
		UserSessions.Delete(username)
		SessionUsers.Delete(session)
	} else {
		logs.Logger.Infof("disconnect session remote:%s->local:%s", session.Conn.RemoteAddr().String(), session.Conn.LocalAddr().String())
	}
}
